<template>
  <div class="node-wrap">
    <div class="node-wrap-box" @click="show">
      <div class="title" style="background: #165dff">
        <icon-send class="icon" />
        <span>{{ nodeConfig.node_name }}</span>
        <el-icon class="close" @click.stop="delNode()"
          ><el-icon-close
        /></el-icon>
      </div>
      <div class="content">
        <span v-if="toText(nodeConfig)">
          <span>
            抄送人员：
            <a-tag
              class="tagss"
              v-for="item in toText(nodeConfig)"
              :key="item"
              color="#165dff"
            >
              <template #icon> <icon-user style="color: white" /> </template
              >{{ item }}</a-tag
            >
          </span>
        </span>
        <span v-else class="placeholder">请选择</span>
      </div>
    </div>
    <add-node v-model="nodeConfig.child_node"></add-node>
    <a-drawer title="审批人设置" :visible="drawer" :width="500" :footer="false">
      <template #header>
        <div
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
          "
        >
          <div class="node-wrap-drawer__title">
            <label @click="editTitle" v-if="!isEditTitle"
              >{{ form.node_name }}
              <icon-edit />
            </label>
            <a-input
              allow-clear
              v-if="isEditTitle"
              ref="nodeTitle"
              v-model="form.node_name"
              :style="{ width: '320px' }"
              @blur="saveTitle"
              @press-enter="saveTitle"
            />
          </div>
          <div
            style="cursor: pointer"
            @click="
              () => {
                drawer = false;
              }
            "
          >
            <icon-close size="15"
          /></div>
        </div>
      </template>
      <a-form ref="formRef" :model="form">
        <a-form-item label="节点类型">
          <a-tag field="node_type" color="arcoblue" style="margin-right: 20px">
            <span style="color: #165dff">抄送节点</span>
          </a-tag>
        </a-form-item>
        <!--        <a-form-item field="copy_type" label="抄送类型">-->
        <!--          <a-select-->
        <!--            disabled-->
        <!--            v-model="form.copy_type"-->
        <!--            placeholder="请选择"-->
        <!--            @change="changeSelect"-->
        <!--          >-->
        <!--            <a-option-->
        <!--              v-for="item in approveOptions"-->
        <!--              :key="item.value"-->
        <!--              :value="item.value"-->
        <!--            >-->
        <!--              {{ item.label }}-->
        <!--            </a-option>-->
        <!--          </a-select>-->
        <!--        </a-form-item>-->
        <a-form-item field="node_assignee_list" label="抄送列表">
          <!-- 指定人员-->
          <!--          <div v-if="form.copy_type === undefined" style="color: green"-->
          <!--            >请选择抄送类型</div-->
          <!--          >-->
          <div>
            <a-row>
              <a-button
                @click="
                  () => {
                    showModel = true;
                  }
                "
              >
                <template #icon>
                  <icon-user />
                </template>
                <template #default>选择人员</template>
              </a-button>
            </a-row>
            <a-space style="margin-top: 10px; display: flex; flex-wrap: wrap">
              <a-tag
                class="tagss"
                v-for="item in showSelectUser"
                :key="item"
                color="#165dff"
              >
                <template #icon>
                  <icon-user style="color: white" />
                </template>

                {{ item.user_name }}</a-tag
              >
            </a-space>
          </div>
          <!--          指定角色-->
          <!--          <div v-if="form.copy_type === 2">-->
          <!--            <a-space> <a-tag color="red">发起人自选</a-tag> </a-space></div-->
          <!--          >-->
        </a-form-item>
        <a-form-item style="margin-top: 30px">
          <a-space>
            <a-button html-type="submit" type="primary" @click="save"
              >保存</a-button
            >
            <a-button @click="$refs.formRef.resetFields()">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-drawer>

    <!--    选择人员  -->
    <a-modal
      title="选择人员"
      :visible="showModel"
      width="600px"
      height="1000px"
      @ok="handleSubmit"
      title-align="start"
      @cancel="
        () => {
          showModel = false;
        }
      "
    >
      <a-row :gutter="5">
        <a-col :span="10">
          <a-card title="部门列表">
            <div style="display: flex; align-items: center; margin-top: 10px">
              <a-spin
                style="
                  margin: 0 auto;
                  margin-top: 20px;
                  min-height: 50px;
                  justify-content: center;
                "
                v-if="loading"
                dot
              />
              <a-tree
                v-else
                default-expand-all
                blockNode
                :data="treeData"
                v-model:checked-keys="selectKeys"
                @select="handleNodeSelect"
                :key="treeKey"
                :check-strictly="true"
              />
            </div>
            <template #extra>
              <a-tooltip content="重置">
                <div @click="resetTable">
                  <icon-loop size="20" />
                </div>
              </a-tooltip>
            </template>
          </a-card>
        </a-col>
        <a-col :span="14">
          <a-card title="人员列表" v-loading="isLoading">
            <a-checkbox-group
              direction="vertical"
              v-model="selectUser"
              v-if="allUser.length > 0"
            >
              <a-checkbox
                v-for="(item, index) in allUser"
                :value="item.user_id"
                >{{ item.user_name }}</a-checkbox
              >
            </a-checkbox-group>
            <a-empty v-else />
          </a-card>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script>
  import addNode from './addNode.vue';
  import { Message } from '@arco-design/web-vue';
  import { transformDeptTree, transformDeptTreeSelect } from '@/utils/utils';
  import { useUserStore } from '@/store';
  import { getDept, getUserList } from '@/api/syssetting';

  export default {
    inject: ['select'],
    props: {
      modelValue: { type: Object, default: () => {} },
    },
    components: {
      addNode,
    },
    data() {
      return {
        showModel: false,
        visible: false,
        nodeConfig: {},
        drawer: false,
        isEditTitle: false,
        loading: false,
        form: {},
        approveOptions: [{ value: 1, label: '指定人员' }],
        isLoading: true,
        currentKeys: '',
        selectKeys: [],
        showSelectUser: [],
        allUser: [],
        selectUser: [],
        treeKey: 0,
        currentCompany: '',
        transformDeptTreeSelect: transformDeptTreeSelect,
        store: useUserStore(),
      };
    },
    watch: {
      modelValue() {
        this.nodeConfig = this.modelValue;
      },
    },
    mounted() {
      this.nodeConfig = this.modelValue;
      this.getDeptList();
      this.getUserAll();
    },
    methods: {
      handleNodeSelect(event, data) {
        this.currentKeys = data.node.id; // 存储第一个选中节点的key
        this.getUserAll();
      },
      resetTable() {
        this.selectKeys = []; // 清空选中的 keys
        this.currentKeys = '';
        this.treeKey = this.treeKey + 1;
        this.getUserAll();
      },
      changeSelect() {
        this.nodeConfig.node_assignee_list = [];
        this.form.node_assignee_list = [];
        this.showSelectUser = '';
      },
      handleSubmit() {
        if (this.selectUser.length <= 0) {
          Message.error('请至少选择一个用户');
          return false;
        }
        const selectedUsers = this.selectUser.map((userId) => {
          const user = this.allUser.find((u) => u.user_id === userId);
          return { user_id: userId, user_name: user?.user_name || '' }; // 确保字段存在
        });
        this.showSelectUser = selectedUsers;
        // 将整合后的数组赋值给表单的 node_assignee_list（用于显示）
        this.form.node_assignee_list = this.selectUser;
        // 关闭模态框
        this.showModel = false;
      },
      async getUserAll() {
        this.isLoading = true;
        const res = await getUserList({
          page_size: 1000,
          user_dept_id: this.currentKeys,
        });
        this.allUser = res.data.list;
        // 创建 id 映射表（优化查找效率）
        this.userMap = new Map(
          this.allUser.map((user) => [user.user_id, user])
        );
        this.isLoading = false;
      },

      getDeptList() {
        getDept({
          page_on: 1,
          page_size: 1000,
        })
          .then((res) => {
            this.loading = true;
            this.treeData = transformDeptTree(res.data.list, '0-0', 'dept_id');
            this.currentKeys = this.treeData[0]?.id;
          })
          .finally(() => {
            this.loading = false;
          });
      },
      show() {
        this.form = {};
        this.form = JSON.parse(JSON.stringify(this.nodeConfig));
        this.drawer = true;
        // 匹配人员
        const selectedUsers = this.form.node_assignee_list.map((userId) => {
          const user = this.store.allUser.find((u) => u.user_id === userId);
          console.log(user);
          return { user_id: userId, user_name: user?.user_name || '' }; // 确保字段存在
        });
        this.showSelectUser = selectedUsers;
      },
      editTitle() {
        this.isEditTitle = true;
        this.$nextTick(() => {
          this.$refs.nodeTitle.focus();
        });
      },
      saveTitle() {
        this.isEditTitle = false;
      },
      save() {
        this.$emit('update:modelValue', this.form);
        this.drawer = false;
      },
      delNode() {
        this.$emit('update:modelValue', this.nodeConfig.child_node);
      },
      delUser(index) {
        this.form.nodeAssigneeList.splice(index, 1);
      },
      selectHandle(type, data) {
        this.select(type, data);
      },
      toText(nodeConfig) {
        const assigneeList = nodeConfig.node_assignee_list || []; // 关键修复行
        return this.store.allUser
          .filter((user) => assigneeList.includes(user.user_id))
          .map((user) => user.user_name);
      },
    },
  };
</script>

<style lang="less" scoped>
  .tagss {
    margin-right: 5px;
    margin-bottom: 5px;
  }
</style>
